package net.tngou.crawler.drug;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.math.NumberUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import net.tngou.c4j.util.HttpUtil;
import net.tngou.cache.CacheEngine;
import net.tngou.cache.TgCacheEngine;
import net.tngou.crawler.util.StringUtil;

/**
 * 华佗药房
 * @author tngou@tngou.net
 *
 */
public class COM_Huatuoyf extends BaseCrawler implements CrawlerDrug{
	private static final Logger log= LoggerFactory.getLogger(COM_Huatuoyf.class);

	private String url="http://www.huatuoyf.com/product/{}.htm";
	
	
	@Override
	public JSONObject getJson(URL url) {
		log.info("请求页面:{}",url.toString());
		Document doc = HttpUtil.get(url.toString());
		if(doc==null||doc.getElementsByClass("sp-SpecialPrice").first()==null)return null;
		json.put("url", url.toString());
		json.put("onlinepharmacy", onlinepharmacy);
		//唯一值
		String[] uns = url.toString().split("/");
		json.put("un",uns[uns.length-1].replaceAll(".htm", "-").split("-")[0]);
		//标签
		Elements mbx = doc.getElementsByClass("mbx");
		if(mbx.first()!=null)
		{
			Elements as = mbx.first().getElementsByTag("a");
			List<String> list = new ArrayList<>();
			for (int i = 1; i < as.size()-2; i++) {
				list.add(as.get(i).text());
			}				
			json.put("tag", list);
		}
		//图片
		Elements jcarousel_list = doc.getElementsByClass("jcarousel-skin-tango");
		if(jcarousel_list.first()!=null)
		{
		
			Elements imgs = jcarousel_list.first().getElementsByTag("img");
			List<String> list = new ArrayList<>();
			imgs.forEach(e->{
				String src = e.attr("src");
				if(StringUtil.isNotEmpty(src))
				{
					list.add(src);
				}
			});
			json.put("picture", list);
		}
		//价格
		Elements price = doc.getElementsByClass("sp-SpecialPrice");
		if(price.first()!=null)
		{	
			String value = price.first().getElementsByTag("span").text();		
			json.put("price", getPrice(value));
			
		}
		//类型
		Element SpecialPrice = doc.getElementById("SpecialPrice");
		if(SpecialPrice!=null)
		{		
			json.put("ptype", Ptype.RX处方药.ordinal());
			
		}else
		{
			json.put("ptype", Ptype.OTC非处方甲类.ordinal());
		}
		//说明书
		Elements instruction = doc.getElementsByClass("xqtable");
		if(instruction.first()!=null)
		{
			JSONObject instructions ;
			if(instruction.size()==2) {
				instructions=instructions_tr_th_td(instruction.get(1));
			}
			else {
				instructions=instructions_tr_th_td(instruction.first());
			}
			json.put("instructions",instructions );
		
		}
		return json;
	}
	

}

